/***
 * 这里存放commander 命令的 所有action 步骤
 */
const { promisify } = require('util')
const path = require('path')
const download = promisify(require('download-git-repo'))
const open = require('open');//打开浏览器
const ora = require('ora');//进度条

const { vueRepo } = require('../config/repo-config')
const { commandSpawn } = require('../utils/terminals')
const { compile, writeToFile, createDirSync } = require('../utils/util')

//创建项目的action
const createProjectAction = async (project) => {
  let process = ora(`下载...${vueRepo}`) //定义一个进度条
  process.start()//启动进度条
  //1.clone 项目
  await download(vueRepo, project);
  process.succeed()//下载完成
  //2.安装依赖 npm install ;  cwd :路径
  // process.platform判断系统执行命令
  const command = process.platform === 'win32' ? 'npm.cmd' : 'npm';
  await commandSpawn(command, ['install'], { cwd: `./${project}` })
  //4.打开浏览器
  open('http://localhost:8080/');
  //3.运行项目 npm run serve
  await commandSpawn(command, ['run', 'serve'], { cwd: `./${project}` })
}


//添加组件的action  name:组件名，dest：组件描述
const addComponentAction = async (name, dest) => {
  //1. 有对应的ejs模块 模版编译
  const result = await compile('vue-component.ejs', { name, lowerName: name.toLowerCase() });
  // console.log(result);
  //2. 编译ejs模版result 将result写入到.vue文件中
  const targetPath = path.resolve(dest, `${name}.vue`)
  console.log(targetPath);
  //4. 放到对应的文件夹
  writeToFile(targetPath, result)
}

//添加组件和路由
const addPageAction = async (name, dest) => {
  //编译模版
  const data = { name, lowerName: name.toLowerCase() }
  const pageResult = await compile('vue-component.ejs', data);
  const routerResult = await compile('vue-router.ejs', data);
  //写入文件
  const targetdest = path.resolve(dest, name.toLowerCase())
  if (createDirSync(targetdest)) {
    const targetPath = path.resolve(targetdest, `${name}/${name}.vue`)
    const targetRouterPath = path.resolve(targetdest, `router.js`)
    writeToFile(targetPath, pageResult)
    writeToFile(targetRouterPath, routerResult)
  }
}

//添加store
const addStoreAction = async (name, dest) => {
  //编译模版
  const storeResult = await compile('vue-store.ejs', {});
  const storeTypesResult = await compile('vue-store-type.ejs', {});
  //写入文件
  const targetdest = path.resolve(dest, name.toLowerCase())
  if (createDirSync(targetdest)) {
    const targetPath = path.resolve(targetdest, `${name}/${name}.js`)
    const targetRouterPath = path.resolve(targetdest, `types.js`)
    writeToFile(targetPath, storeResult)
    writeToFile(targetRouterPath, storeTypesResult)
  }
}



module.exports = {
  createProjectAction,
  addComponentAction,
  addPageAction,
  addStoreAction
};